﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Cn.Edwon.Web {
    public class HtmlUtil {
        /// <summary>
        /// 清除HTML格式
        /// </summary>
        /// <param name="rStr"></param>
        /// <returns></returns>
        public static String CleanHtml(String rStr) {
            if (!String.IsNullOrEmpty(rStr)) {
                rStr = Regex.Replace(rStr, "<(h[1-6]|div|address|pre|form|table|li|ol|ul|td|b|em|strong|strike|u|span|a|ul|ol|li|blockquote)([^\\|>]*?)>", "", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "</(h[1-6]|div|address|pre|form|table|li|ol|ul|td|b|em|strong|strike|u|span|a|ul|ol|li|blockquote)([^\\|>]*?)>", "", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "<(br)([^\\|>]*?)\\/>", "<br>", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "<(br)(\\s{1,}?)\\>", "<br>", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "</p([^\\|>]*?)>", "</p>", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "<p([^\\|>]*?)>", "", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "</p>", "<br><br>", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "&nbsp;", "", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "<br>", " ", RegexOptions.IgnoreCase);
            }
            return rStr;
        }
        /// <summary>
        /// 解码HTML内容，将转义字符解释为＜和＞
        /// </summary>
        /// <param name="rStr"></param>
        /// <returns></returns>
        public static String DecodeHtml(String rStr) {
            if (!String.IsNullOrEmpty(rStr)) {
                rStr = rStr.Replace("&lt;", "<");
                rStr = rStr.Replace("&gt;", ">");
            }
            return rStr;
        }
        /// <summary>
        /// 编码HTML内容，将＜和＞解释为转义字符
        /// </summary>
        /// <param name="rStr"></param>
        /// <returns></returns>
        public static String EncodeHtml(String rStr) {
            if (!String.IsNullOrEmpty(rStr)) {
                rStr = rStr.Replace("<","&lt;");
                rStr = rStr.Replace(">", "&gt;");
            }
            return rStr;
        }
    }
}
